#!/bin/sh

set -eu

NODE_KIND=$1
if [ $NODE_KIND == "pumps" ]; then
    NODE_ID=$2
    STATE=$3
else
    NODE_ID="drainer"
    STATE=$2
fi

OUT_DIR=/tmp/tidb_binlog_test
STATUS_LOG="${OUT_DIR}/status.log"
max_commit_ts_old=0
max_commit_ts_new=0

for i in {1..15}
do
    binlogctl -ssl-ca $OUT_DIR/cert/ca.pem \
        -ssl-cert $OUT_DIR/cert/client.pem \
        -ssl-key $OUT_DIR/cert/client.key \
        -pd-urls https://127.0.0.1:2379 -cmd $NODE_KIND -show-offline-nodes > $STATUS_LOG 2>&1
    cat $STATUS_LOG

    if [ $NODE_KIND == "pumps" ]; then 
        count=`grep "$NODE_ID" $STATUS_LOG | grep -c "$STATE" || true`
    else
        count=`grep -c "$STATE" $STATUS_LOG || true`
    fi

    if [ $i -eq 1 ]; then
        max_commit_ts_old=`cat $STATUS_LOG | sed 's/.*MaxCommitTS: \([0-9]*\), .*/\1/g'`
    else
        max_commit_ts_new=`cat $STATUS_LOG | sed 's/.*MaxCommitTS: \([0-9]*\), .*/\1/g'`
    fi

    # if status is online, will check the max commit ts, the new max commit ts should greater than the old one.
    if [ $count -ne 1 ] || ([ $STATE == "online" ] && [ $max_commit_ts_new -le $max_commit_ts_old ]); then
        if [ $i -eq 15 ]; then
            echo "${NODE_ID}'s status is not $STATE, or max commit ts is not update, old max commit ts is $max_commit_ts_old, new max commit ts is $max_commit_ts_new"
            exit 2
        else
            sleep 1
        fi
    else
        break
    fi
done
